const router = require('koa-router')()
const uploader = require('../upload')
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stats = require('../helper/stats')
const rename = util.promisify(fs.rename)
const comments = require('./comments')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.prefix('/images')


router.post('/', uploader.single('file'),async function(ctx, next){
  let file = ctx.req.file
  let diskFilename = file.filename + path.extname(file.originalname)
  await rename(file.path, path.dirname(file.path) + '/' + diskFilename)
  .then(() => Image.create({
        title:ctx.req.body.title,
        description:ctx.req.body.description,
        filename:diskFilename,
        originalname:ctx.req.file.originalname,
        mimetype:ctx.req.file.mimetype
  }))
  .then(doc =>ctx.redirect(`/images/${doc.id}`))
  .catch(err =>ctx.throw(500,err))
})

router.get('/:imageid', async function(ctx, next) {
  await Promise.all([
    Image.findByIdAndUpdate(ctx.params.imageid,{$inc:{views:1}}),
    Image.findById(ctx.params.imageid),
    Image.find().sort({likes: -1}).limit(9),
    stats(),
    Comment.find({image:ctx.params.imageid}),
    Comment.find().sort({timestamp: -1}).limit(9).populate('image')
  ])
  .then(([view,image, popular, stats, comments]) => ctx.render('image',
        {image,popular, stats, comments }
))
  .catch(err =>ctx.throw(500,err))
})

//点赞
router.post('/:id/like', async ctx =>{
  await Image.findByIdAndUpdate(ctx.params.id,{$inc:{likes: 1}})
  .then(() =>Image.findById(ctx.params.id))
  .then(doc =>ctx.body = {likes: doc.likes})
  .catch(err=> ctx.throw(500,err))
})


//删除
router.del('/:id' ,async ctx =>{
    await Image.findByIdAndRemove(ctx.params.id)
    //删除图片的同时删除评论
    .then(()=> Comment.deleteMany({image:ctx.params.id}))
    .then(() =>ctx.body ={ok: 1})
    .catch(err => ctx.throw(500,err))
})

router.use('/:imageid/comment', comments.routes(), comments.allowedMethods())
module.exports = router
